package com.dtwave.wechat.service.provider.web.wx;

import com.dtwave.dubbo.DubboResult;
import com.dtwave.wechat.service.provider.common.utils.FileUtils;
import com.dtwave.wechat.service.provider.common.utils.URLEncodeUtil;
import com.dtwave.wechat.service.provider.dto.NotifyDto;
import com.dtwave.wechat.service.provider.service.INotifyService;
import com.dtwave.wechat.service.provider.web.BaseController;
import com.dtwave.wolf.utils.BizPreconditions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: liuwenxiang
 * @Date: 2019/2/26 09:36
 * @Description:
 */

@Api(description = "通知通告")
@Controller
@CrossOrigin
@RequestMapping("${url.common.path}/notify")
public class NotifyController extends BaseController {


    @Autowired
    INotifyService iNotifyService;



    @Value("${spring.resources.static-locations}")
    private  String fileDir;



    /**
     * @param
     *  userId:通知通告创建人id/通知通告接受人id,
     *  status:0暂存,1提交
     *  type:publish发布，unpublish暂存,check签收，uncheck未签收
     * @param request
     * @return List<Map<String, Object>>
     */
    @ApiOperation(value="通知通报列表",notes="")
    @RequestMapping(value = "/notify_list", method = RequestMethod.GET)
    @ResponseBody
    public DubboResult list(@RequestParam String userId , @RequestParam String status,@RequestParam String type,HttpServletRequest request) {
        Map<String,Object> map=new HashMap<String,Object>();
        try {
            if(StringUtils.isNotEmpty(status)&&("1").equals(status)){
                //当前登录人发布的通知通报列表
                List<Map<String, Object>>  list =  iNotifyService.getNotifyList(userId,type);
                map.put("data",list);
            }else{
                //当前登录人接收的通知通报列表
                List<Map<String, Object>>  list =  iNotifyService.getReceiveNotifyList(userId,type);
                map.put("data",list);
            }
            map.put("success", true);
            map.put("msg", "成功");
        }catch (Exception e){
            map.put("success", false);
            map.put("msg", "失败");
            logger.error("通知通报查看列表异常：",e);
        }
        return DubboResult.buildSuccessResult(map);
    }


    /**
     *
     * @param
     *   userId:当前登录人
     *   notifyId:通知通告id
     *   type:publish发布，unpublish暂存,check签收，uncheck未签收（从哪里点击进入详情，uncheck这个位置进入的会有一个已读未读的判断）
     * @param request
     * @return Map<String,Object>
     */
    @ApiOperation(value="通知通报详情",notes="")
    @RequestMapping(value = "/notify_detail", method = RequestMethod.GET)
    @ResponseBody
    public DubboResult detail(@RequestParam String userId , @RequestParam Integer notifyId,@RequestParam String type, HttpServletRequest request) {
        Map<String,Object> map=new HashMap<String,Object>();
        try {
            //设置通知通报已读状态
            if(StringUtils.isNotEmpty(type)&&("uncheck").equals(type)){
                iNotifyService.setReadFlag(notifyId,userId);
            }
            //查看通知通报详情
            Map<String,Object> detail = iNotifyService.notifyDetail(notifyId);//详情
            List<Map<String, Object>> list = iNotifyService.getReceiverList(notifyId);//接受人列表
            detail.put("reciever_list", list);
            map.put("data", detail);
            map.put("success", true);
            map.put("msg", "成功");
        }catch (Exception e){
            map.put("success", false);
            map.put("msg", "失败");
            logger.error("通知通报查看详情异常：",e);
        }
        return DubboResult.buildSuccessResult(map);
    }


    /**
     *
     * @param notifyDto
     *   userId:当前登录人
     *   notifyId:通知通告id
     *   type:publish发布，unpublish暂存,check签收，uncheck未签收（从哪里点击进入详情，uncheck这个位置进入的会有一个已读未读的判断）
     * @param request
     * @return Map<String,Object>
     */
    @ApiOperation(value="通知通报签收",notes="")
    @RequestMapping(value = "/notify_check", method = RequestMethod.POST)
    @ResponseBody
    public DubboResult check(@RequestBody NotifyDto notifyDto , HttpServletRequest request) {
        BizPreconditions.checkArgument(notifyDto != null, "参数(notifyDto)不可为空");
        Map<String,Object> map=new HashMap<String,Object>();
        String userId = notifyDto.getUserId();
        Integer notifyId = notifyDto.getNotifyId();
        String type = notifyDto.getType();
        try {
            if(StringUtils.isNotEmpty(type)&&("uncheck").equals(type)){
                iNotifyService.notifyCheck(notifyId,userId);
            }
            map.put("success", true);
            map.put("msg", "成功");
        }catch (Exception e){
            map.put("success", false);
            map.put("msg", "失败");
            logger.error("通知通报签收异常：",e);
        }
        return DubboResult.buildSuccessResult(map);
    }



    /**
     *
     * @param notifyDto
     *   notifyId:通知通告id
     *   type:类型
     *   title:标题
     *   content:内容
     *   files:文件
     *   status:状态
     *   userId:创建人
     *   receiveList:接受人列表
     * @param request
     * @return Map<String,Object>
     */
    @ApiOperation(value="通知通报发布",notes="")
    @RequestMapping(value = "/notify_publish", method = RequestMethod.POST)
    @ResponseBody
    public DubboResult publish(@RequestBody NotifyDto notifyDto , HttpServletRequest request) {
        BizPreconditions.checkArgument(notifyDto != null, "参数(notifyDto)不可为空");
        Map<String,Object> map=new HashMap<String,Object>();
        try {
            iNotifyService.notifyPublish(notifyDto);
            map.put("success", true);
            map.put("msg", "成功");
        }catch (Exception e){
            map.put("success", false);
            map.put("msg", "失败");
            logger.error("通知通报发布异常：",e);
        }
        return DubboResult.buildSuccessResult(map);
    }


    /**
     *
     * @param
     * @param request
     * @return
     */
    @ApiOperation(value="文件上传",notes="")
    @RequestMapping(value = "/upload_file", method = RequestMethod.POST)
    @ResponseBody
    public DubboResult uploadFile(@RequestParam  MultipartFile[] files,HttpServletRequest request) {
        Map<String,Object> map=new HashMap<String,Object>();
        String fileSplit = fileDir .split(":")[1];
        StringBuffer stringBuffer=new StringBuffer();
        String returnurl="";
        try {
            for (MultipartFile file:files) {

                String originalFilename = file.getOriginalFilename();
                String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String date =sdf.format(new Date());
                //构建目录和文件

                String dir = fileSplit+"/"+date+"/"+FileUtils.getFileType(fileExt);
                String fileName = URLEncodeUtil.getRandomString(10)+"."+fileExt;
                //创建目录和文件
                FileUtils.createDirectory(dir);
                FileUtils.createFile(dir+"/"+fileName);
                logger.info(fileDir+"目录"+dir);

                //文件上传
                FileUtils.copyInputStreamToFile(file.getInputStream(),new File(dir+"/"+fileName));
                returnurl=date+"/"+FileUtils.getFileType(fileExt)+"/"+fileName;
                stringBuffer.append(returnurl).append(",");
            }
            String data=stringBuffer.toString();
            map.put("data",StringUtils.isNotEmpty(data)?data.substring(0,data.length()-1):null);
            map.put("success", true);
            map.put("msg", "成功");
        }catch (IOException e){
            map.put("success", false);
            map.put("msg", "失败");
            logger.error("文件上传发生异常",e);
        }
        return DubboResult.buildSuccessResult(map);
    }







}